const User = require('../models/user')

exports.signup = (req, res) => {
  let _user = req.body.user
  User.find({ name: _user.name }, (err, user) => {
    if (err) console.log(err)
    if (user.length > 0) {
      return res.redirect('/')
    } else {
      user = new User(_user)
      user.save(function (err, user) {
        if (err) return console.log(err)

        res.redirect('/admin/userlist')
      })
    }
  })
}

exports.singin = (req, res) => {
  const _user = req.body.user
  const name = _user.name
  const password = _user.password

  User.findOne({ name: name }, (err, user) => {
    if (err) return console.log(err)
    if (!user) {
      return res.redirect('/')
    }
    user.comparePassword(password, (err, isMatch) => {
      if (err) return console.log(err)
      if (isMatch) {
        req.session.user = user
        console.log('密码正确')
        return res.redirect('/')
      } else {
        console.log('密码错误')
      }
    })
  })
}

exports.logout = (req, res) => {
  delete req.session.user
  res.redirect('/')
}

exports.list = (req, res) => {
  User.fetch((err, user) => {
  if (err) return console.log(err)
    res.render('userlist', {
      title: '用户列表页',
      users: user
    })
  })
}


exports.showSignin = (req, res) => {
  res.render('signin', {
    title: '登录页面'
  })
}

exports.showSignup = (req, res) => {
  res.render('signup', {
    title: '注册页面'
  })
}